import { IFeidaoAiNodejsPage } from '@feidao/web/interfaces';

import generate from '@feidao/web/atom/nodejs/url/query2url';
import check_user from '@feidao/web/atom/nodejs/authorization/check';
import is_online from '@feidao/web/atom/nodejs/msg/user-isonline';
import set_code from '@feidao/web/atom/nodejs/server/status-code';

import return_fail from '@feidao/web/atom/nodejs/server/return-fail';
import redirect from '@feidao/web/atom/nodejs/server/redirect';
import obj_mixin from '@feidao/web/atom/core/obj/mixin';

import storage_put from '@feidao/web/atom/nodejs/storage/put';


function set_url(feidao_data: IFeidaoAiNodejsPage) {
	const obj = {
		backurl: feidao_data.data.url
	};
	return generate(obj, 'login.html');
}

export default async function check(feidao_data: IFeidaoAiNodejsPage) {
	const line = await is_online();
	if (line) {
		const res = await check_user();
		if (!res.result) {
			const code = set_code(403);
			return return_fail(code);
		} else {
			const auth_code = res.auth_code;
			await storage_put('auth_code', auth_code, 'page');
		}
	} else {
		const url = set_url(feidao_data);
		const r = redirect(url);
		return return_fail(r);
	}
}